package com.plusjun.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.plusjun.common.constant.AuthServerConstant;
import com.plusjun.common.exception.BizCodeEnum;
import com.plusjun.common.utils.R;
import com.plusjun.common.vo.MemberRespVO;
import com.plusjun.gulimall.auth.feign.MemberFeignService;
import com.plusjun.gulimall.auth.feign.ThirdPartFeignService;
import com.plusjun.gulimall.auth.vo.UserLoginVO;
import com.plusjun.gulimall.auth.vo.UserRegistVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collector;
import java.util.stream.Collectors;


@Controller
public class LoginAndRegisterController {
    @Resource
    ThirdPartFeignService thirdPartFeignService;

    @Resource
    MemberFeignService memberFeignService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null) {
            return "login";
        }
        return "redirect:http://gulimall.com";
    }

    /**
     * 获取验证码
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendSms(@RequestParam("phone") String phone) {
        // TODO 1、接口防刷
        // 2、先在redis中寻找，看看有没有相同的key，并且两次发送验证码的时间有没有隔1分钟
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PRIFIX + phone).toString();
        if (StringUtils.isNotEmpty(s)) {
            long l = Long.parseLong(s.substring(5));
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        // 3、如果以上通过，则先向redis中存入code，在调用短信接口发送验证码
        String code = UUID.randomUUID().toString().substring(0, 5) + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PRIFIX + phone, code.substring(0,5), 300, TimeUnit.SECONDS);
        thirdPartFeignService.sendCode(phone, code.substring(0,5));
        return R.ok();
    }

    /**
     * TODO 重定向携带数据，利用session原理，将数据放在session中，
     * 只要跳到下一页去除数据后，session中数据就会被删除
     *
     * TODO 解决分布式下的session问题
     * @param vo
     * @param result
     * @param attributes
     * @return
     */
    @PostMapping("/regist")
    public String register(@Valid UserRegistVO vo, BindingResult result, RedirectAttributes attributes) {

        if (result.hasErrors()) {
            Collector<FieldError, ?, Map<String, String>> errors = Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage);
            // 使用RedirectAttributes，重定向之后还能渠道数据
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";

        }
        // 校验验证码
        String codeFromHtml = vo.getCode();
        Map<String,String> errors = new HashMap<>();
        System.out.println(AuthServerConstant.SMS_CODE_CACHE_PRIFIX + vo.getPhone());
        String codeFromRedis =  redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PRIFIX + vo.getPhone()).toString();
        if(StringUtils.isNotEmpty(codeFromRedis)) {
            if(Objects.equals(codeFromHtml,codeFromRedis.substring(0,5))) {
                // 验证码通过，删除验证码
                //redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PRIFIX + vo.getPhone());
                //  调用远程服务注册

                R r = memberFeignService.regist(vo);
                if(r.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    errors.put("msg", (String) r.getData(new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",errors);

                    return "redirect:http://auth.gulimall.com/register.html";
                }

            } else{
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/register.html";
            }
        } else {
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }


        // 注册成功，重定向到登录页
        //return "redirect:http://auth.gulimall.com/login.html";
    }



    @PostMapping("/login")
    public String login(UserLoginVO vo, RedirectAttributes attributes, HttpSession session){
        Map<String, String> errors = new HashMap<>();
        if(vo.getPassword().trim() != "" && vo.getLoginacct().trim() != "") {
            R r = memberFeignService.login(vo);
            if(r.getCode() == 0) {
                MemberRespVO data = (MemberRespVO) r.getData("data", new TypeReference<MemberRespVO>() {
                });
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                return "redirect:http://gulimall.com";
            } else {
                errors.put("msg", (String) r.getData(new TypeReference<String>(){}));
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            errors.put("msg","账号或密码不能为空或非法字符");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
